import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/common/widget/underline_text_field.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/core/utils/toast_utils.dart';

import 'package:casdon/modules/login/application/notifier/login_update_pwd_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_type_notifier.dart';
import 'package:casdon/modules/login/domain/states/login_code_state.dart';
import 'package:casdon/modules/login/domain/states/update_pwd_state.dart';
import 'package:casdon/modules/login/domain/usecases/check_account_usecase.dart';

import 'package:casdon/modules/login/providers/login_provider.dart';
import 'package:casdon/auto_router.dart';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';

@RoutePage()
class ForgetPwdScreen extends ConsumerStatefulWidget {
  final int gapSize = 24;
  const ForgetPwdScreen({super.key});

  @override
  ConsumerState<ForgetPwdScreen> createState() => _ForgetPwdScreenState();
}

class _ForgetPwdScreenState extends ConsumerState<ForgetPwdScreen> {
  String screenId = "ForgetPwdScreen";
  late final ProviderSubscription<UpdatePwdState> _forgetPwdSubscription;
  @override
  void initState() {
    super.initState();
    _setupListeners();
  }

  void _setupListeners() {
    _forgetPwdSubscription = ref.listenManual<UpdatePwdState>(
      loginModifyPwdNotifierProvider,
      (pri, next) => _handleUpdatePwdState(pri, next),
    );
  }

  @override
  void dispose() {
    _forgetPwdSubscription.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final inputValidator = ref.watch(inputValidatorProvider);

    final isLoading = ref.watch(
      loginModifyPwdNotifierProvider.select(
        (s) => s.status == CommonNetStatus.loading,
      ),
    );

    final accountEditingController = ref.watch(
      editingControllerProvider(screenId),
    );
    final isValid = inputValidator.isValude(accountEditingController.text);
    final notifier = ref.watch(loginModifyPwdNotifierProvider.notifier);
    final state = ref.watch(loginModifyPwdNotifierProvider);
    final isEnabled = !isLoading;

    return Scaffold(
      appBar: CommonAppBar(title: ""),
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: true,
      body: SafeArea(
        child: KeyboardAvoider(
          duration: const Duration(milliseconds: 300),
          autoScroll: true,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                SizedBox(height: 25.h),
                Text(
                  "忘记密码",
                  style: context.textTheme.displayLarge!.copyWith(
                    color: context.customColorThemeNonNull.textColor1,
                  ),
                ),
                SizedBox(height: 35.h),
                UnderlineTextField(
                  controller: accountEditingController,
                  hintText: "手机号或邮箱",
                  keyboardType: TextInputType.emailAddress,
                  onChanged: (value) {
                    notifier.updateAccount(value);
                  },
                  validator: null,
                ),

                SizedBox(height: 32.h),
                PrimaryButton(
                  text: '获取验证码',
                  onPressed: isEnabled
                      ? () {
                          _handleSendVerifyCode(context, ref);
                        }
                      : null,
                  isLoading: isLoading,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _handleUpdatePwdState(UpdatePwdState? pri, UpdatePwdState next) {
    if (!mounted) return;
    final notifier = ref.read(loginModifyPwdNotifierProvider.notifier);

    if (notifier.step == UpdatePwdtep.sendCode) {
      if (next.source == SendCodeSource.accountPage) {
        if (next.status == CommonNetStatus.success) {
          CodeInputRoute(account: next.account!).push(context);
        } else if (next.status == CommonNetStatus.failure) {
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      }
    }
  }

  void _handleSendVerifyCode(BuildContext context, WidgetRef ref) async {
    final notifier = ref.read(loginModifyPwdNotifierProvider.notifier);
    final currentState = ref.read(loginModifyPwdNotifierProvider);
    final account = currentState.account;
    if (account == null || account.isEmpty) {
      ToastUtil.show("请输入账号");
      return;
    }
    final inputValidator = ref.watch(inputValidatorProvider);
    if (inputValidator.isValude(account) == false) {
      ToastUtil.show("账号格式不正确");
      return;
    }

    final checkAccountUsecase = ref.read(checkAccountUsecaseProvider);

    try {
      await checkAccountUsecase.execute(userName: account);
    } on BusinessException catch (e) {
      if (e.code == "10003") {
        ToastUtil.show("该账户未注册");
        return;
      } else {
        ToastUtil.show(e.msg);
      }
      rethrow;
    }

    ref.read(loginTypeProvider.notifier).state = LoginType.updatePwd;
    await notifier.sendCode();
  }
}
